const mysql = require('mysql2/promise');
const fs = require('fs');
const path = require('path');

async function setupDatabase() {
    console.log('=================================');
    console.log('趣味英语 - 数据库初始化');
    console.log('=================================\n');

    // 数据库配置 - 如果密码不对，请在这里修改
    const config = {
        host: 'localhost',
        user: 'root',
        password: 'Lycc.2025',
        charset: 'utf8mb4',
        multipleStatements: true
    };

    let connection;

    try {
        console.log('正在连接MySQL...');
        connection = await mysql.createConnection(config);
        console.log('✅ MySQL连接成功\n');

        // 创建数据库
        console.log('正在创建数据库 fun_english_db...');
        await connection.query('CREATE DATABASE IF NOT EXISTS fun_english_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci');
        console.log('✅ 数据库创建成功\n');

        // 选择数据库
        await connection.query('USE fun_english_db');

        // 读取并执行简化版init.sql
        console.log('正在执行初始化脚本...');
        const sqlPath = path.join(__dirname, 'init-simple.sql');
        const sql = fs.readFileSync(sqlPath, 'utf8');
        
        // 分割SQL语句并逐个执行
        const statements = sql.split(';').filter(stmt => stmt.trim());
        for (const statement of statements) {
            if (statement.trim()) {
                await connection.query(statement);
            }
        }
        console.log('✅ 数据表创建成功\n');

        // 检查表
        const [tables] = await connection.query('SHOW TABLES');
        console.log('已创建的数据表:');
        tables.forEach(table => {
            console.log('  ✓', Object.values(table)[0]);
        });

        console.log('\n=================================');
        console.log('✅ 数据库初始化完成！');
        console.log('下一步: 运行 node vocabulary-import.js');
        console.log('=================================\n');

    } catch (error) {
        console.error('❌ 错误:', error.message);
        if (error.code === 'ER_ACCESS_DENIED_ERROR') {
            console.log('\n💡 提示: MySQL密码可能不正确');
            console.log('请修改 database/setup-database.js 文件第13行的密码');
            console.log('然后重新运行: node setup-database.js\n');
        }
        process.exit(1);
    } finally {
        if (connection) {
            await connection.end();
        }
    }
}

setupDatabase();
